package com.budwk.app.sys.services.impl;

import cn.hutool.core.bean.BeanUtil;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sys.models.Sys_dict;
import com.budwk.app.sys.vo.SysDictVO;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.app.sys.models.Sys_dict_new;
import com.budwk.app.sys.services.SysDictNewService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.aop.interceptor.async.Async;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.plugins.wkcache.annotation.CacheRemoveAll;
import org.nutz.plugins.wkcache.annotation.CacheResult;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@IocBean(args = {"refer:dao"})
public class SysDictNewServiceImpl extends BaseServiceImpl<Sys_dict_new> implements SysDictNewService {
    public SysDictNewServiceImpl(Dao dao) {
        super(dao);
    }
    
        @Override
        @CacheResult
        public List<Sys_dict_new> getSubListByCode(String code) {
            Sys_dict_new dict = this.fetch(Cnd.where("code", "=", code));
            return dict == null ? new ArrayList<>() : this.query(Cnd.where("parentId", "=", Strings.sNull(dict.getId())).asc("location"));
        }

        /**
         * 通过父id获取下级列表
         *
         * @param id ID
         * @return
         */
        @Override
        @CacheResult
        public List<Sys_dict_new> getSubListById(String id) {
            return this.query(Cnd.where("parentId", "=", Strings.sNull(id)).asc("location"));
        }


        @Override
        @Aop(TransAop.READ_COMMITTED)
        public void save(Sys_dict_new dict, String pid) {
            String path = "";
            if (!Strings.isEmpty(pid)) {
                Sys_dict_new pp = this.fetch(pid);
                path = pp.getPath();
            }
            dict.setPath(getSubPath("sys_dict", "path", path));
            dict.setParentId(pid);
            dao().insert(dict);
            if (!Strings.isEmpty(pid)) {
                this.update(Chain.make("hasChildren", true), Cnd.where("id", "=", pid));
            }
        }

        @Override
        @Aop(TransAop.READ_COMMITTED)
        public void deleteAndChild(Sys_dict_new dict) {
            //dao().execute(Sqls.create("delete from shequ.sys_dict where path like @path").setParam("path", dict.getPath() + "%"));
            //if (!Strings.isEmpty(dict.getParentId())) {
            //    int count = count(Cnd.where("parentId", "=", dict.getParentId()));
            //    if (count < 1) {
            //        dao().execute(Sqls.create("update shequ.sys_dict set hasChildren=0 where id=@pid").setParam("pid", dict.getParentId()));
            //    }
            //}

            // wzy 2023-10-20 改写字典表删除方法 之前通过path判断的会造成误删
            List<String> deleteIdList = Lists.newArrayList(dict.getId());
            deleteIdList.addAll(getAllSubId(dict.getId()));

            delete(deleteIdList);
        }

        @Override
        @CacheRemoveAll
        @Async
        public void cacheClear() {

        }

        @Override
        public List<SysDictVO> getDictTree(Sys_dict_new queryDict) {
            // 这个逻辑是查询第一级然后将剩下的数据都查询出来
            Cnd cnd = Cnd.NEW();
            if (StringUtils.isNotBlank(queryDict.getCode())) cnd.and("code", "=", queryDict.getCode());
            List<Sys_dict_new> list = query(cnd);

            List<SysDictVO> resultList = org.apache.commons.compress.utils.Lists.newArrayList();
            for (Sys_dict_new sysDict : list) {
                SysDictVO vo = new SysDictVO();
                BeanUtil.copyProperties(sysDict, vo);
                vo.setLabel(sysDict.getName());
                popularChildren(vo);
                resultList.add(vo);
            }

            return resultList;
        }

        @Override
        public List<Sys_dict_new> listDictByName(String dictName) {
            if (StringUtils.isEmpty(dictName)) {
                throw new AppException("缺少请求参数！");
            }
            Sys_dict_new sysDict = this.fetch(Cnd.where(Sys_dict_new::getName, "=", dictName));
            if (sysDict == null) {
                throw new AppException("请联系管理员先添加数据字典项！");
            }
            List<Sys_dict_new> list = this.query(Cnd.where(Sys_dict_new::getParentId, "=", sysDict.getId()));
            return list;
        }

        private void popularChildren(SysDictVO parentDict) {
            List<Sys_dict_new> subList = getSubListById(parentDict.getId());
            if (subList.size() > 0) {
                List<SysDictVO> resultList = org.apache.commons.compress.utils.Lists.newArrayList();

                for (Sys_dict_new sysDict : subList) {
                    SysDictVO vo = new SysDictVO();
                    BeanUtil.copyProperties(sysDict, vo);
                    vo.setLabel(sysDict.getName());
                    popularChildren(vo);

                    resultList.add(vo);
                }

                parentDict.setChildren(resultList);
            }
        }

        private List<String> getAllSubId(String parentId) {
            List<String> allSubId = Lists.newArrayList();
            Cnd cnd = Cnd.NEW();
            cnd.and("parentid", "=", parentId);
            List<Sys_dict_new> subDictList = query(cnd);
            allSubId.addAll(subDictList.stream().map(Sys_dict_new::getId).collect(Collectors.toList()));
            if (subDictList.size() > 0) {
                for (Sys_dict_new subDict : subDictList) {
                    allSubId.addAll(getAllSubId(subDict.getId()));
                }
            }

            return allSubId;
        }
}
